//
//  ZYHomeController.m
//  CirclePush
//
//  Created by admin on 2018/4/8.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "ZYHomeController.h"



#import "WYRecommendController.h"
#import "TLCityPickerController.h"
#import "WYHomeRecommendCell.h"
#import "WYRecommendCell.h"
#import "WYHomeHeaderController.h"
#import "WYSearchReusltController.h"
@interface ZYHomeController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,TLCityPickerDelegate,PYSearchViewControllerDelegate>
@property (nonatomic,strong)WYTableView *tableView;
@property (nonatomic,strong)SDCycleScrollView *scrollview;
@property (nonatomic, strong) SDCycleScrollView *advView;
@property (nonatomic, strong) UIButton *searchButton;
@property (nonatomic,strong)WYRecommendController *recommendVC;
@property (nonatomic,strong)UIImageView *lineView;
@property (nonatomic,strong)WYHomeHeaderController *headVC;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)NSArray *bannerArray;
@property (nonatomic,strong)WYImageModel *imageMedel;
@property (nonatomic,strong) NSString *height;

@property (nonatomic,strong)NSString *cityName;
@property (nonatomic,strong)UIButton *leftBarBtn;
@end

@implementation ZYHomeController
{
    BOOL _isrefresh;
    NSUInteger _page;
}
-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray=[[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (UIImageView *)getLineViewInNavigationBar:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self getLineViewInNavigationBar:subview];
        if (imageView) {
            return imageView;
        }
    }
    
    return nil;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.lineView = [self getLineViewInNavigationBar:self.navigationController.navigationBar];
    self.lineView.hidden = YES;
    
}
- (void)viewDidLoad
{
   [super viewDidLoad];
    _page=1;
    [self setupUI];
    [self loadData];
    [self loadBannerList];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTabbarSelect) name:@"changeTabbarSelect" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(editChageHeaderView:) name:@"editRowHeight" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickHotMedia:) name:@"clickHotMedia" object:nil];
//     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeCellHeight:) name:@"editCollectionViewHeight" object:nil];
    
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeCellHeight:) name:@"testChangeHeight" object:nil];
    
    
    //NSLog(@"%f",STATUSBAR_HEIGHT);
}
-(void)changeCellHeight:(NSNotification *)notification
{
    if (!self.height.length) {
        NSString *height=[notification.userInfo[@"height"] stringValue];
        self.height=height;
        CGRect newFrame = self.headVC.view.frame;
        if (height.floatValue<40) {
            
        }else{
             newFrame.size.height = newFrame.size.height+height.floatValue+60;
        }
       
        self.headVC.view.frame = newFrame;
        [self.tableView beginUpdates];
        [self.tableView setTableHeaderView:self.headVC.view];
        [self.tableView endUpdates];
    }
}



-(void)changeTabbarSelect
{
    [self.tabBarController setSelectedIndex:2];
}
-(void)clickHotMedia:(NSNotification *)notification
{
    NSLog(@"%@",notification);
}
-(void)editChageHeaderView:(NSNotification *)not
{
     CGFloat height = [not.object[@"height"] floatValue];
    if (kDevice_Is_iPhoneX) {
        height+=50;
    }else{
        height+=20;
    }
    
    CGRect newFrame = self.headVC.view.frame;
    newFrame.size.height = newFrame.size.height+height+140;
    self.headVC.view.frame = newFrame;
    [self.tableView beginUpdates];
    [self.tableView setTableHeaderView:self.headVC.view];
    [self.tableView endUpdates];
}

-(void)loadBannerList
{
    WEAKSELF
    [WYHttpServer getImageListWithtType:@"1" SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            weakSelf.bannerArray = [WYImageModel getImageModelFromJson:response[@"result"]];
            if (weakSelf.bannerArray.count) {
                NSMutableArray *array = [[NSMutableArray alloc]init];
                for (WYImageModel *model in weakSelf.bannerArray) {
                    [array addObject:model.image];
                }
                weakSelf.advView.imageURLStringsGroup = array;
            }
            
            
            
        }
    }];
   
    
}
-(void)loadData
{
    WEAKSELF
    [WYHttpServer getRecommendMediaListWithmediaId:@"" Witharea:self.cityName WithPageNum:@(_page) WithPageSize:@"10" SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
       
        NSLog(@"%@",errorMessage);
        if (success) {
            if ([WYMedia getMediaListFromJson:response[@"result"]].count) {
                [weakSelf.dataArray addObjectsFromArray:[WYMedia getMediaListFromJson:response[@"result"]]];
                [weakSelf.tableView reloadData];
                [self.tableView.mj_footer endRefreshing];
            }
           
        }else{
            
        }
    }];
}








-(void)setupUI
{
    self.tableView.contentInset = UIEdgeInsetsMake(IMAGE_HEIGHT, 0, 0, 0);
    [self.tableView addSubview:self.advView];
    [self setupNavItems];
    [self wr_setNavBarBarTintColor:[UIColor whiteColor]];
    [self wr_setNavBarBackgroundAlpha:0];
    [self wr_setNavBarTintColor:[UIColor whiteColor]];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"WYRecommendCell" bundle:nil] forCellReuseIdentifier:@"WYRecommendCell"];
    [self.view addSubview:self.tableView];
    self.headVC = [[WYHomeHeaderController alloc]init];
    self.headVC.view.frame = CGRectMake(0, 0, kScreenWidth, 185+(kScreenWidth-20)/1.61+50+100);
    self.tableView.tableHeaderView = self.headVC.view;
    self.headVC.tableView.bounces = NO;
    self.headVC.tableView.scrollEnabled = NO;
//    WEAKSELF
//    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        _isrefresh=NO;
//        _page++;
//        [weakSelf loadData];
//    }];
}




- (void)setupNavItems
{
    UIView *leftView = [[UIView alloc]init];
    //leftView.backgroundColor = [UIColor yellowColor];
    UILabel *nameLabel = [[UILabel alloc]init];
    [leftView addSubview:nameLabel];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.centerY.mas_equalTo(leftView);
    }];
    
    UIImageView *bottomView = [[UIImageView alloc]init];
    [leftView addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(nameLabel).offset(-2);
        make.left.equalTo(nameLabel.mas_right).offset(5);
        make.width.mas_equalTo(12);
        make.height.mas_equalTo(7);
    }];
    bottomView.image = [UIImage imageNamed:@"iocn_bottom_arrow"];
    nameLabel.text = @"北京市";
    nameLabel.textColor = [UIColor whiteColor];
    nameLabel.font = [UIFont systemFontOfSize:13];
    
    UIButton *tapButton = [[UIButton alloc]init];
    [leftView addSubview:tapButton];
    [tapButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.top.mas_equalTo(0);
    }];
    [tapButton addTarget:self action:@selector(onClickLeft) forControlEvents:UIControlEventTouchUpInside];

    UIButton *button = [[UIButton alloc]init];
    button.frame = CGRectMake(0, 0, 70, 44);
    [button setTitle:@"北京市" forState:(UIControlStateNormal)];
    [button setImage:[UIImage imageNamed:@"icon_down_arrow"] forState:UIControlStateNormal];
    button.titleEdgeInsets = UIEdgeInsetsMake(0, -30, 0, 0);
    button.imageEdgeInsets = UIEdgeInsetsMake(0, 60, 0, 0);
    [button addTarget:self action:@selector(onClickLeft) forControlEvents:(UIControlEventTouchUpInside)];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    self.leftBarBtn = button;
//    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"北京市" style:(UIBarButtonItemStylePlain) target:self action:@selector(onClickLeft)];
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = leftButtonItem;

    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"search-1"] style:UIBarButtonItemStylePlain target:self action:@selector(onClickRight)];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
      CGFloat offsetY = scrollView.contentOffset.y;
//    if (offsetY < -IMAGE_HEIGHT) {
//        [self updateNavBarButtonItemsAlphaAnimated:.0f];
//    } else {
//        [self updateNavBarButtonItemsAlphaAnimated:1.0f];
//    }

    if (offsetY > 64)
    {
        CGFloat alpha = (offsetY - 64) / 64;
        [self wr_setNavBarBackgroundAlpha:alpha];
        [self wr_setNavBarTintColor:[[UIColor blackColor] colorWithAlphaComponent:alpha]];
        [self wr_setNavBarTitleColor:[[UIColor blackColor] colorWithAlphaComponent:alpha]];
        [self wr_setStatusBarStyle:UIStatusBarStyleDefault];
        [self.leftBarBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    }
    else
    {
        [self wr_setNavBarBackgroundAlpha:0];
        [self wr_setNavBarTintColor:[UIColor whiteColor]];
        [self wr_setNavBarTitleColor:[UIColor whiteColor]];
        [self.leftBarBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        // [self wr_setNavBarTintColor:[UIColor blackColor]];
    }

    //限制下拉的距离
//    if(offsetY < LIMIT_OFFSET_Y) {
//        [scrollView setContentOffset:CGPointMake(0, LIMIT_OFFSET_Y)];
//    }
}

//- (void)updateNavBarButtonItemsAlphaAnimated:(CGFloat)alpha
//{
//    [UIView animateWithDuration:0.2 animations:^{
//        [self.navigationController.navigationBar wr_setBarButtonItemsAlpha:alpha hasSystemBackIndicator:NO];
//    }];
//}

//- (void)updateSearchBarColor:(CGFloat)alpha
//{
//    UIColor *color = [[UIColor colorWithRed:29/255.0 green:160/255.0 blue:126/255.0 alpha:1.0] colorWithAlphaComponent:alpha];
//    UIImage *image = [UIImage imageNamed:@"search"];
//    image = [image wr_updateImageWithTintColor:color alpha:alpha];
//    [self.searchButton setBackgroundImage:image forState:UIControlStateNormal];
//    [self.searchButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//}

#pragma mark - tableview delegate / dataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    WYRecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYRecommendCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"WYRecommendCell" owner:nil options:nil].firstObject;
    }
    [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
    WYMedia *media = self.dataArray[indexPath.row];
    [cell setMedia:media];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // [self.tabBarController setSelectedIndex:2];
    WYMediaDetailController *mdc = [[WYMediaDetailController alloc]init];
    WYMedia *media = self.dataArray[indexPath.row];
    mdc.ID = media.id;
    [self.navigationController pushViewController:mdc animated:YES];
    
    //  NSLog(@"%ld---%ld",indexPath.section,indexPath.row);
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
    UIView *lineView = [[UIView alloc]init];
    [view addSubview:lineView];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.centerY.mas_equalTo(view);
        make.width.mas_equalTo(5);
        make.height.mas_equalTo(15);
    }];
    lineView.backgroundColor = [UIColor blueColor];
    
    UILabel *label = [[UILabel alloc]init];
    [view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(15);
        make.centerY.mas_equalTo(view);
        
    }];
    
    label.text = @"媒体推荐";
    
    UIView *bottomLineView = [[UIView alloc]init];
    [view addSubview: bottomLineView];;
    [bottomLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.mas_equalTo(0);
        make.height.mas_equalTo(kLineHeight);
    }];
    
    bottomLineView.backgroundColor = [UIColor hexStringToColor:@"#e6e6e6" alpha:1.0];
    view.backgroundColor = [UIColor whiteColor];
    
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
#pragma mark - getter / setter
- (UITableView *)tableView
{
    if (_tableView == nil) {
        CGRect frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-self.tabHeight);
        _tableView = [[WYTableView alloc] initWithFrame:frame
                                                  style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (UIImage *)imageWithImageSimple:(UIImage *)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(CGSizeMake(newSize.width*2, newSize.height*2));
    [image drawInRect:CGRectMake (0, 0, newSize.width*2, newSize.height*2)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
- (void)onClickLeft
{
    TLCityPickerController *cityPickerVC = [[TLCityPickerController alloc] init];
    [cityPickerVC setDelegate:self];
    
    // 设置定位城市
   // cityPickerVC.locationCityID = @"1400010000";
    
    // 最近访问城市，如果不设置，将自动管理
    //  cityPickerVC.commonCitys = [[NSMutableArray alloc] initWithArray: @[@"1400010000", @"100010000"]];
    
    // 热门城市，需手动设置
    cityPickerVC.hotCitys = @[@"100010000", @"200010000", @"300210000", @"600010000", @"300110000"];
    
    // 支持push、present方式跳入，但需要有UINavigationController
    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:cityPickerVC] animated:YES completion:^{
    }];
}
#pragma mark - TLCityPickerDelegate
- (void) cityPickerController:(TLCityPickerController *)cityPickerViewController didSelectCity:(TLCity *)city
{
    [self.leftButton setTitle:city.cityName forState:UIControlStateNormal];
    self.cityName = city.cityName;
    [self.leftBarBtn setTitle:city.cityName forState:(UIControlStateNormal)];
   // self.navigationItem.leftBarButtonItem.title=city.cityName;
    [cityPickerViewController dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void) cityPickerControllerDidCancel:(TLCityPickerController *)cityPickerViewController
{
    [cityPickerViewController dismissViewControllerAnimated:YES completion:^{
        
    }];
}


- (void)onClickRight
{
//    NSArray *hotSeaches = @[@"Java", @"Python", @"Objective-C", @"Swift", @"C", @"C++", @"PHP", @"C#", @"Perl", @"Go", @"JavaScript", @"R", @"Ruby", @"MATLAB"];
    // 2. Create a search view controller
    PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:@[] searchBarPlaceholder:@"请输入搜索内容" didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        // Called when search begain.
        // eg：Push to a temp view controller
        WYSearchReusltController *src = [[WYSearchReusltController alloc]init];
        src.searchTitle = searchText;
        [searchViewController.navigationController pushViewController:src animated:YES];
    }];
    searchViewController.hotSearchStyle = PYHotSearchStyleDefault;
    searchViewController.searchHistoryStyle = PYSearchHistoryStyleDefault;
    searchViewController.delegate = self;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchViewController];
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)onClickSearchBtn
{
    
    NSArray *array = @[@"http://imgsrc.baidu.com/imgad/pic/item/cb8065380cd79123499f23a0a7345982b3b780e3.jpg",@"http://img18.3lian.com/d/file/201709/19/b35e13d1416c91c7a15621ec41f7fea1.jpg",@"http://d.hiphotos.baidu.com/zhidao/pic/item/ae51f3deb48f8c541fe2f2b73c292df5e0fe7f70.jpg"];
    [self.advView setImageURLStringsGroup:array];
    
}

- (int)navBarBottom
{
    if ([WRNavigationBar isIphoneX]) {
        return 88;
    } else {
        return 64;
    }
}
- (SDCycleScrollView *)advView
{
    if (_advView == nil) {
        _advView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, -IMAGE_HEIGHT, kScreenWidth, IMAGE_HEIGHT) imageNamesGroup:nil];
        _advView.pageDotColor = [UIColor grayColor];
        _advView.autoScrollTimeInterval = 2;
        _advView.currentPageDotColor = [UIColor whiteColor];
        _advView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    }
    return _advView;
}






@end
